import data from "../core/cache_data";
import GameTask from "../core/game_task";
import { HttpRequest, Http } from "../core/http_request";
import Macro from "../core/macro";
import Utils from "../core/utils";

const { ccclass, property } = cc._decorator;

@ccclass
export default class GameTaskWx extends GameTask {
    async init() {
        let opt = new HttpRequest(`https://res.wx.qq.com/open/js/jweixin-${data.gameConfig.wxConfig.sdkVersion}.js`);
        let scriptStr = "";
        try {
            scriptStr = await new Promise<string>((ok, fail) => {
                Http.download(opt, (bolb) => {
                    let reader = new FileReader();
                    reader.readAsText(bolb);
                    reader.onload = () => {
                        ok(<string>reader.result);
                    }
                }, (e) => {
                    fail(e);
                });
            });
        }
        catch (e) {
            console.error("GameTaskWx::init, 下载wx库失败。", e);
        }
        if (scriptStr) {
            Utils.LoadScript(scriptStr, "weixin");
        }

        if (Macro.BUILD_TARGET != "dev" && data.gameConfig.wxConfig.enabled) {
            await this.initWx();
        }
        this.onFinished();
    }
    async initWx() {
        let dat = null;
        try {
            let res = await HttpRequest.Get(data.gameConfig.wxConfig.getSignUrl, {
                url: encodeURIComponent(window.location.href)
            }).reqPromise();

            dat = res.data;
        }
        catch (e) {
            console.error("GameTaskWx::initWx, error:", e);
        }
        if (dat) {
            //@ts-ignore
            wx.config({
                debug: false,
                appId: dat.appid,
                timestamp: dat.timestamp,
                nonceStr: dat.nonce_str,
                signature: dat.signature,
                jsApiList: [
                    'checkJsApi',
                    'onMenuShareQQ',
                    'onMenuShareWeibo',
                    'onMenuShareQZone',

                    'onMenuShareTimeline',
                    'onMenuShareAppMessage'
                ]
            });
            //@ts-ignore
            wx.ready(this.onWxReady.bind(this));
        }

    }

    onWxReady() {
        try {
            Utils.msgHub.emit(Utils.macro.EVENTS.WX_READY);
        } catch (e) { }
        try {
            console.log("微信事件播放声音，成功。");
        } catch (e) {
            console.warn("微信事件播放声音，失败。");
        }

        this.shareConfig(
            data.gameConfig.wxConfig.shareTitle,
            data.gameConfig.wxConfig.shareDesc,
            `${window.location.href}`,
            `${window["GamePath"]}/${data.gameConfig.wxConfig.shareImgUrl}`,
            null
        );
    }

    shareConfig(title, desc, shareUrl, imgUrl, onShareFinish) {
        //@ts-ignore
        if (!wx) {
            console.warn("GameTaskWx::shareConfig, warn: 没有找到 wx");
            return;
        }
        var shareInfoAppMessage = {
            title: title,
            desc: desc,
            link: shareUrl,
            imgUrl: imgUrl,
            type: 'link',
            dataUrl: '',
            success: this.onShareFinish.bind(this),
            cancel: this.onShareFinish.bind(this)
        };
        //@ts-ignore
        wx.onMenuShareAppMessage(shareInfoAppMessage);

        var shareInfoTimeLine = {
            title: title + "。" + desc,
            link: shareUrl,
            imgUrl: imgUrl,
            success: this.onShareFinish.bind(this),
            cancel: this.onShareFinish.bind(this)
        };
        //@ts-ignore
        wx.onMenuShareTimeline(shareInfoTimeLine);

        console.log("shareConfig:", shareInfoAppMessage, shareInfoTimeLine);

        this._onShareFinish = onShareFinish;
    }
    _onShareFinish: () => void = null;
    onShareFinish() {
        this._onShareFinish && this._onShareFinish();
    }
};  